import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/singer_card.dart';

import '../../models/user_model.dart';
import '../../services/user_service.dart';

class SingerPage extends StatefulWidget {
  const SingerPage({Key? key}) : super(key: key);

  @override
  _SingerPageState createState() => _SingerPageState();
}

class _SingerPageState extends State<SingerPage>
    with AutomaticKeepAliveClientMixin {
  late EasyRefreshController _controller;
  List<UserItem> _singerList = UserList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    _getSinger();
  }

  Future _getSinger({bool push = false}) async {
    List<dynamic> result =
        await UserService.getUsers(type: "DQ_SINGER", page: page);
    UserList singerListModel = UserList.fromJson(result);
    setState(() {
      //hasMore
      page++;
      if (push) {
        _singerList.addAll(singerListModel.list);
      } else {
        _singerList = singerListModel.list;
      }
    });
  }

  FutureOr _onRefresh() async {
    page = 1;
    await _getSinger();
    _controller.finishRefresh();
    _controller.resetFooter();
  }

  FutureOr _onLoad() async {
    await _getSinger(push: true);
    _controller.finishLoad();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _controller,
      header: ClassicHeader(),
      footer: ClassicFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: GridView.builder(
        itemCount: _singerList.length,
        itemBuilder: (BuildContext context, int index) {
          bool isEven = index.isEven;
          double pl = isEven ? 18 : 9;
          double pr = isEven ? 9 : 18;
          return Container(
            padding: EdgeInsets.only(left: pl, right: pr),
            color: Colors.white,
            child: SingerCard(
              userItem: _singerList[index],
            ),
          );
        },
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: MediaQuery.of(context).size.width / 2,
          mainAxisExtent: MediaQuery.of(context).size.height / 2.8,
          mainAxisSpacing: 8,
          crossAxisSpacing: 1,
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
